<template>
    <ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" @expand="getTableH"></ZwSearchForm>
    <ZwTable
        ref="tableRef"
        class="table-box"
        :tab-h="'435'"
        :option="tableOption"
        :fetch-params="state.searchParams"
        :fetch-api="fetchApi()">
        <template #headerOperate>
            <el-button type="primary" @click="bindOrderHandler"> 绑定店铺订单 </el-button>
        </template>
    </ZwTable>
    <Dialog :app-dialog="appDialog">
        <el-form :model="formData" label-width="90px">
            <el-form-item label="会员信息">
                {{ member_info.nickname || '--' }}（{{ member_info.mobile || '--' }}）
            </el-form-item>
            <el-form-item label="订单编号" required>
                <el-input v-model="formData.orderNo" clearable placeholder="请输入订单编号" />
                <div class="tip">*订单绑定成功后，系统会将该用户在该店铺已同步到客易达系统的历史订单自动绑定。</div>
            </el-form-item>
        </el-form>
    </Dialog>
</template>
<script setup lang="tsx">
import { reactive, ref, computed, nextTick, onMounted } from 'vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Dialog from '@/components/Dialog.vue';
import { memberOrder } from '@/api/member/memberList/index';
import { getMemberChannelList, bindShopOrder } from '@/api/member/memberList/index';
import { getWiseManList } from '@/api/ecommerce/wiseManList';
import { defaultTime } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { ElMessage } from 'element-plus';
const props = defineProps(['member_no', 'member_info']);
const emit = defineEmits(['searchData']);
const tableRef = ref<any>(null);
const searchOption = computed(() => {
    return [
        {
            label: '归属店铺',
            name: 'shop_id',
            value: [],
            type: 'select',
            placeholder: '请选择店铺',
            popperClass: 'zw-hide_select_option',
            isStoreSelect: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '归属达人',
            name: 'daren_openid',
            type: 'select',
            value: '',
            clearable: true,
            placeholder: '全部',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getWiseManList({ auth_status: [2, 3], page: 1, page_size: 999 }).then((res: any) => {
                        const targetArr: any = [];
                        res?.data?.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.daren_name,
                value: v.daren_openid
            })
        },
        {
            label: '下单时间',
            name: 'order_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: defaultTime(),
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '订单来源',
            name: 'order_channel',
            type: 'select',
            value: [],
            clearable: true,
            placeholder: '全部',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 1 };
                    getMemberChannelList({ type: 2 }).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const tableOption = [
    {
        prop: 'external_order_id',
        label: '订单编号',
        minWidth: 150,
        render({ row, column, index }: any) {
            return <elPopoverTips content={row.external_order_id} />;
        }
    },
    {
        prop: 'source',
        label: '订单来源',
        width: 100,
        render({ row, column, index }: any) {
            return <div>{row.source || '--'}</div>;
        }
    },
    {
        prop: 'state',
        label: '订单状态',
        width: 80,
        render({ row, column, index }: any) {
            return <div>{row.state || '--'}</div>;
        }
    },
    {
        prop: 'external_user_account',
        label: '购买账号',
        minWidth: 120,
        render({ row, column, index }: any) {
            return <elPopoverTips content={row.external_user_account} />;
        }
    },
    {
        prop: 'cope_amount',
        label: '应付/实付金额(元)',
        width: 180,
        render({ row, column, index }: any) {
            return <div>{(row.cope_amount ?? '--') + '/' + (row.actually_amount ?? '--')}</div>;
        }
    },
    {
        prop: 'retail_shop_name',
        label: '归属店铺/达人',
        minWidth: 180,
        render({ row, column, index }: any) {
            const isShop = row.source_type == 1;
            const src = `/static/member/${isShop ? 'shop' : 'member'}-icon-small.png`;
            const name = isShop ? row.retail_shop_name : row.daren_name;
            return (
                <div style="display: flex;align-items:center;">
                    <el-image
                        style="display: inline-block;width: 16px; height: 16px;margin-right: 4px;"
                        v-show={name}
                        src={src}></el-image>
                    {name || '--'}
                </div>
            );
        }
    },
    {
        prop: 'store_code_name',
        label: '关联门店',
        render({ row, column, index }: any) {
            return <div>{row.store_code_name || '--'}</div>;
        }
    },
    {
        prop: 'belong_staff',
        label: '归属员工',
        width: 80,
        render({ row, column, index }: any) {
            return <div>{row.belong_staff || '--'}</div>;
        }
    },
    {
        prop: 'order_time',
        label: '下单时间',
        width: 155,
        render({ row, column, index }: any) {
            return <div>{row.order_time || '--'}</div>;
        }
    }
];
const defaultParams = {
    member_no: props.member_no,
    order_time: [],
    order_channel: '',
    shop_id: '',
    daren_openid: ''
};

const formData = reactive({
    orderNo: null
});

const state = reactive({
    searchParams: deepCopy(defaultParams)
});

const fetchApi = () => {
    getTableH();
    return memberOrder;
};
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
onMounted(() => {
    getTableH();
});

const search = (data: any) => {
    state.searchParams = deepCopy({ ...defaultParams, ...data });
    emit('searchData');
};

const reset = () => {
    state.searchParams = deepCopy({ ...defaultParams });
};

/**
 * 点击绑定店铺订单按钮
 */
const bindOrderHandler = () => {
    formData.orderNo = null;
    appDialog.visible = true;
};
/**
 * 确定绑定订单
 */
const bindOrderSubmitHander = async () => {
    if (!formData?.orderNo?.trim()) {
        ElMessage.error('请填写订单编号');
        return;
    }
    await bindShopOrder({ member_no: props.member_no, external_order_id: formData?.orderNo?.trim() });
    ElMessage.success('订单绑定成功');
    // 延迟调接口
    setTimeout(() => {
        tableRef.value.reload();
    }, 500);
    appDialog.visible = false;
};

const appDialog = reactive({
    visible: false,
    title: `绑定订单`,
    width: '40%',
    cancel: () => {
        appDialog.visible = false;
    },
    submit: bindOrderSubmitHander,
    cancelText: '取消',
    submitText: '确定'
});
</script>
<style lang="scss" scoped>
.text_over {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
}

.shop-daren {
    display: flex;
    align-items: center;

    &-icon {
        display: inline-block;
        width: 16px;
        height: 16px;
    }
}
.tip {
    margin-top: 8px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 22px;
}
</style>
